package main

import (
	"github.com/ngaut/log"
	"global/structs"
	"server/kline/model"
	"sync"
)

type Data struct {
	sync.Mutex
	CoinPair map[string]structs.CoinPair
}

func NewData() *Data {
	data := &Data{
		CoinPair: make(map[string]structs.CoinPair),
	}
	data.InitCoinPair()
	return data
}

func (d *Data) InitCoinPair() {
	pairs, err := model.CoinPairModel.GetAll()
	if err != nil {
		log.Fatalf("init coin pair data error, msg: %s", err.Error())
	}

	for _, pair := range pairs {
		d.CoinPair[pair.Name] = pair
	}
}

// 检查交易对是否存在
func (d *Data) CheckCoinPairExists(pairName string) bool {
	d.Lock()
	defer d.Unlock()
	if _, ok := d.CoinPair[pairName]; ok {
		return  true
	}
	return false
}

// 添加交易对
func (d *Data) AddCoinPair(pair structs.CoinPair) {
	if _, ok := d.CoinPair[pair.Name]; !ok {
		d.Lock()
		d.CoinPair[pair.Name] = pair
		d.Unlock()
	}
}

// 移除交易对
func (d *Data) RemoveCoinPair(pairName string) {
	if _, ok := d.CoinPair[pairName]; ok {
		d.Lock()
		delete(d.CoinPair, pairName)
		d.Unlock()
	}
}
